﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;

namespace WeChatDataSrc
{
    class ForeCheckData
    {
        static string DayForeURL = ConfigurationSettings.AppSettings["DayForeURL"];
        /// <summary>
        /// 上传数据
        /// </summary>
        public static void UploadData(DateTime? sd)
        {
            DateTime NowMaxDateTime;

            string ReadResult = ReadMax.ReadMaxDayFore();
            string NowMaxSpan = "00";

            if (ReadResult != "none")
            {
                NowMaxSpan = ReadResult.Split('|')[1].Split('_')[0].Substring(2);
                if (DateTime.TryParse(ReadResult.Split('|')[0], out NowMaxDateTime) == false)
                {
                    NowMaxDateTime = DateTime.Now.AddDays(-2);
                }
            }
            else
            {
                NowMaxDateTime = DateTime.Now.AddDays(-2);
            }
            if (sd.HasValue)
            {
                NowMaxDateTime = Convert.ToDateTime(sd).AddDays(-2);
            }
            string[] Spans = { "FD00_24", "FD24_48", "FD48_72", "FD72_96", "FD96_120", "FD120_144", "FD144_168" };

            foreach (var Span in Spans)
            {
                if (Convert.ToInt32(Span.Split('_')[0].Substring(2)) >= Convert.ToInt32(NowMaxSpan))
                {
                    string data = GetData(Span, NowMaxDateTime);
                    if (data == null) continue;
                    HttpPost.SendData(DayForeURL, "data=" + data);
                }
            }
        }

        private static void WriteData(string data)
        {
            using (StreamWriter writer = new StreamWriter("log.txt",true))
            {
                writer.Write(data);
            }
        }

        private static void Send(List<string> data)
        {
            if (data != null)
            {
                foreach (var item in data)
                {
                    HttpPost.SendData(DayForeURL, item);
                }
            }
        }

        private static string GetData(string span, DateTime time)
        {
            List<string> Result = new List<string>();
            DateTime Now = DateTime.Now;
            List<DayForeModel> Results = new List<DayForeModel>();
            while (true)
            {
                if (DateTime.Compare(time, Now) > 0)
                {
                    break;
                }
                List<String> FilterSendPoint = new List<string>();
                string sql = string.Format("select * from Normal_CityFore where [date]='{0}' and span='{1}' and semitype='Auto' and type='{2}' and [sendpoint] > 'H05' order by sendpoint desc", time.ToString("yyyyMMdd"), span, "wth");
                DataTable dt = SqlHelper.ExecuteDataset(SqlHelper.CityFore_ConnectionString, CommandType.Text, sql).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        DataRow dr = dt.Rows[i];
                        if (FilterSendPoint.Contains(dr["sendpoint"].ToString()))
                        {
                            continue;
                        }
                        FilterSendPoint.Add(dr["sendpoint"].ToString());
                        string semi = dr["semi"].ToString();
                        if (semi != "")
                        {
                            string[] values = semi.Split('|');
                            foreach (var v in values)
                            {
                                string correct = "0", empty = "0", leave = "0", others = "0";
                                if (v.Split(';')[2] == "1")
                                {
                                    correct = "1";
                                }
                                else if (v.Split(';')[2] == "2")
                                {
                                    empty = "1";
                                }
                                else if (v.Split(';')[2] == "3")
                                {
                                    leave = "1";
                                }
                                else
                                {
                                    others = "1";
                                }
                                Results.Add(new DayForeModel() { date = time.ToString("yyyy-MM-dd"), station = v.Split(';')[0], span = span, sendpoint = dr["sendpoint"].ToString(), correct = correct, empty = empty, leave = leave, others = others });
                            }
                        }
                        else
                        {
                        }
                    }

                }
                else
                {
                    
                }

                sql = string.Format("select * from Normal_CityFore where [date]={0} and span='{1}' and semitype='Auto' and type in ('maxt','mint') order by sendpoint desc", time.ToString("yyyyMMdd"), span);
                dt = SqlHelper.ExecuteDataset(SqlHelper.CityFore_ConnectionString, CommandType.Text, sql).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        DataRow dr = dt.Rows[0];
                        string semi = dr["semi"].ToString();
                        if (semi != "")
                        {
                            string[] values = semi.Split('|');
                            foreach (var v in values)
                            {
                                string maxt = "0", mint = "0";
                                DayForeModel obj = Results.Where(x => x.station == v.Split(';')[0] && x.span == span && x.sendpoint == dr["sendpoint"].ToString() && x.date == time.ToString("yyyy-MM-dd")).FirstOrDefault();
                                if (obj != null)
                                {
                                    if (dr["type"].ToString() == "maxt")
                                    {
                                        obj.maxt = v.Split(';')[1];
                                    }
                                    else
                                    {
                                        obj.mint = v.Split(';')[1];
                                    }
                                }
                                else
                                {

                                }
                            }
                        }
                    }
                }
                time = time.AddDays(1);
            }

            if (Results.Count == 0)
            {
                return null;
            }
            StringBuilder sb = new StringBuilder();
            System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();
            ser.Serialize(Results, sb);
            return sb.ToString();

        }
    }
    class DayForeModel
    {
        public DayForeModel()
        {
            date = "";
            station = "";
            correct = "0";
            empty = "0";
            leave = "0";
            others = "0";
            maxt = "0";
            mint = "0";
            span = "";
            sendpoint = "";
        }
        public string date { get; set; }
        public string station { get; set; }
        public string correct { get; set; }
        public string empty { get; set; }
        public string leave { get; set; }
        public string others { get; set; }
        public string maxt { get; set; }
        public string mint { get; set; }
        public string span { get; set; }
        public string sendpoint { get; set; }
    }
}
